<?php

require_once 'Zend/Config/Ini.php';
require_once 'Zend/Application.php';

class Jnd_App {
  protected static $_env = null;
  /**
   * @var Zend_Application
   */
  protected static $_application = null;
  
  /**
   * @var Zend_Session_Namespace|Jnd_Environnement
   */
  protected static $_environnement = null;

  public static function getEnv() {

    return self::$_env;
  }

  protected static function _setEnv( $env ) {

    self::$_env = $env;
  }

  public static function getBootstrap() {

    return self::$_application->getBootstrap();
  }

  public static function bootstrap( $env, $appConfig = null ) {

    self::_setEnv($env);
    
    // Merge de la configuration de l'application
    $cfg = new Zend_Config_Ini(FRAMEWORK_PATH . '/application/configs/application.ini', $env, array(
      'allowModifications' => true
    ));
    if( ! empty($appConfig) && file_exists($appConfig) ) {
      $cfg->merge(new Zend_Config_Ini($appConfig, $env));
    }
    $cfg->setReadOnly();
    // Initialisation de l'application
    self::$_application = new Zend_Application($env, $cfg);
    self::$_application->bootstrap();
    return self::$_application;
  }

  public static function run( $env, $appConfig = null ) {

    $application = self::bootstrap($env, $appConfig);
    return $application->run();
  }

  public static function getConfig( $param = '' ) {

    $config = self::getBootstrap()->getOption($param);
    return $config;
  }

  public static function getResource( $resource ) {

    $resource = self::getBootstrap()->getResource($resource);
    return $resource;
  }
  
  /**
   * @return Zend_Session_Namespace|Jnd_Environment
   */
  public static function getEnvironnement()
  {
      if (self::$_environnement === null) {
          $config = self::getConfig('appli');
          self::$_environnement = Jnd_Environment::factory($config['trigramme']);
      }
      return self::$_environnement;
  }

}
